package com.example.everying.service.statistics.impl;/*
 * 项目名称: everything
 * 文件名: UserSessionServiceImpl
 * 作者: 张泽阳
 * 日期: 2025/7/7
 * 描述:
 */

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.everying.context.UserContext;
import com.example.everying.mapper.statistics.UserSessionMapper;
import com.example.everying.model.dto.statistics.UserStatDto;
import com.example.everying.model.entity.statistics.SystemActivityStats;
import com.example.everying.model.entity.statistics.UserSession;
import com.example.everying.service.statistics.SystemActivityStatsService;
import com.example.everying.service.statistics.UserSessionService;
import com.example.everying.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Service
public class UserSessionServiceImpl extends ServiceImpl<UserSessionMapper, UserSession> implements UserSessionService {
    @Autowired
    private SystemActivityStatsService systemActivityStatsService;
    @Override
    public Result<?> recordLogin() {

        long timestamp = System.currentTimeMillis(); // 2023-01-01 00:00:00 UTC

// 指定时区转换
        LocalDateTime loginTime = Instant.ofEpochMilli(timestamp)
                .atZone(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        UserSession userSession = new UserSession();
        userSession.setUserId(UserContext.getUser().getId());
        userSession.setLoginTime(loginTime);
        userSession.setCreateTime(LocalDateTime.now());
        userSession.setUpdateTime(LocalDateTime.now());
        userSession.setStatus(1);
        int flag = baseMapper.insert(userSession);
        if(flag > 0){
            return Result.ok("记录用户登录时间成功");
        }
        return Result.fail("记录用户登录时间失败");
    }

    @Override
    public Result<?> recordLogout() {

        long timestamp = System.currentTimeMillis(); // 2023-01-01 00:00:00 UTC

// 指定时区转换
        LocalDateTime logoutTime = Instant.ofEpochMilli(timestamp)
                .atZone(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        UserSession userSession = new UserSession();
        userSession.setUserId(UserContext.getUser().getId());
        userSession.setLogoutTime(logoutTime);
        userSession.setUpdateTime(LocalDateTime.now());
        userSession.setStatus(0);
        int flag = baseMapper.updateLastTimeUserSessionByUserId(userSession);
        return Result.ok("记录用户登出时间成功");
    }

    @Override
    public Result<?> averageUseTime() {
        List<SystemActivityStats> userActiveTime = baseMapper.getUserActiveTime(LocalDate.now().minusDays(7), LocalDate.now().minusDays(1));
        return Result.ok(userActiveTime);
    }

    @Override
    public Result<?> loginCount() {
        return Result.ok(baseMapper.getLoginCount(LocalDate.now().minusDays(7), LocalDate.now().minusDays(1)));
    }

    @Override
    public Result<?> rr1() {
        return Result.ok(baseMapper.getRr1(LocalDate.now().minusDays(1)));
    }

    @Override
    public Result<?> rr7() {
        return Result.ok(baseMapper.getRr7(LocalDate.now().minusDays(1)));
    }

    @Override
    public Result<?> onlineUserCount() {
        // 当前日期的00:00:00
        LocalDateTime startTime = LocalDateTime.now()
                .withHour(0)
                .withMinute(0)
                .withSecond(0);
        LocalDateTime endTime = LocalDateTime.now();
        List<SystemActivityStats> onlineUserCount = baseMapper.getOnlineUserCount(startTime,endTime);
        System.out.println(onlineUserCount);
        return Result.ok(onlineUserCount);
    }

    @Override
    public List<String> getUserIdsByTime(LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.getUserIdsByTime(startTime, endTime);
    }

    @Override
    public int getStatCohortCount(LocalDate statDate, LocalDate cohortDate) {
        return baseMapper.getStatCohortCount(statDate, cohortDate);
    }

    /**
     * 获取指定日期登录的去重用户
     * @param date
     * @return
     */
    @Override
    public List<String> getDistinctUsersByDate(LocalDate date) {
        return baseMapper.getDistinctUsersByDate(date);
    }



    @Override
    public Result<?> conversionStatistics() {
        return Result.success(baseMapper.conversionStatistics());
    }

    @Override
    public Result<?> completionRate() {
        return Result.success(baseMapper.completionRate());
    }

    @Override
    public Result<?> totalAmount() {
        return Result.success(baseMapper.totalAmount());
    }

    @Override
    public Result<?> recurrentRate() {
        return Result.success(baseMapper.recurrentRate());
    }

    @Override
    public Result<?> repurchaseRate() {
        return Result.success(baseMapper.repurchaseRate());
    }

    @Override
    public Result<?> userLoginCount(UserStatDto userStatDto) {
        LocalDateTime endDateTime = LocalDateTime.now();
        LocalDateTime startDateTime = endDateTime.minusDays(7).withHour(0).withMinute(0).withSecond(0);
        return Result.ok(baseMapper.getUserLoginCount(startDateTime, endDateTime, userStatDto.getUserId()));
    }

    @Override
    public Result<?> userLoginDuration(UserStatDto userStatDto) {
        LocalDateTime endDateTime = LocalDateTime.now();
        LocalDateTime startDateTime = endDateTime.minusDays(7).withHour(0).withMinute(0).withSecond(0);
        return Result.ok(baseMapper.getUserLoginDuration(startDateTime, endDateTime, userStatDto.getUserId()));
    }



    /**
     * 根据用户id获取用户会话信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserSession getUserSessionByUserId(String userId) {
        return baseMapper.getUserSessionByUserId(userId);
    }

    @Override
    public Result<?> getTopTenArticle() {
        LocalDateTime endDateTime = LocalDateTime.now();
        LocalDateTime startDateTime = LocalDateTime.now()
                .withHour(0)
                .withMinute(0)
                .withSecond(0);
        return Result.ok(baseMapper.getTopTenArticle(startDateTime, endDateTime));
    }
}
